#include "stdafx.h"
#include "Brassica.h"

//Basic module to load a local file and pipe the contents along
//Reads name of file to open through input pipe

#define ALLOC_INC 256;

VOID BRASSICA_API File(PIPEHANDLE PipeIn, PIPEHANDLE PipeOut){
	BYTE *buffer;
	BYTE temp;
	if (!PipeRead(PipeIn, &temp, 1) || temp != 0x02)
		throw "Invalid input to File module";

	SIZE_T bytes, bytesallocd = 0;
	while (TRUE){
		bytesallocd += ALLOC_INC;
		if (!(buffer = realloc(buffer, bytesallocd)))
			throw "Error allocating memory";
		if (PipeRead(PipeIn, &buffer[bytesallocd - ALLOC_INC], ALLOC_INC) < ALLOC_INC)
			break;
	}
	//buffer filled and sized
	HANDLE hFile;
	{
		TCHAR *fname = (TCHAR)buffer;
		if (!(hFile = CreateFile(fname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)))
			throw "Error opening file";
	}

	free(buffer);

	DWORD fsize;
	fsize = GetFileSize(hInFile, NULL);

	buffer = malloc(fsize);

	DWORD bytesread;
	ReadFile(hFile, buffer, fsize, &bytesread, NULL);
	PipeWrite(PipeOut, buffer, bytesread);
	free(Buffer);
}